import modelExtend from 'dva-model-extend'
import {lwjPageModel} from 'utils/model'
import pathToRegexp from 'path-to-regexp'
import {routerRedux} from 'dva/router'
import {query, updateCart, deleteCart, cartCaluate} from './service'

export default modelExtend(lwjPageModel, {
  namespace: 'cartList',
  state: {
    productsList: [],
    totalChannelPrice: 0.00,
    totalRetailPrice: 0.00,
    totalPrice: 0.00,
    count: 0,
    selectedRowKeys: [],
    selectedRows: [],
    selectedDistributorId: '-1'
  },
  subscriptions: {
    setup({dispatch, history}) {
      history.listen(({pathname, search}) => {
        const match = pathToRegexp('/salesmarket/cartList').exec(pathname);
        let distributorIdMatch = search.match(/id=(.*)$/);
        if(match) {
          dispatch({
            type: 'reset',
            selectedDistributorId: (distributorIdMatch && distributorIdMatch.length > 0 ? distributorIdMatch[1] : '-1')
          })
          dispatch({
            type: 'query'
          })
          dispatch({
            type: 'setSelectedRowKeys',
            selectedRows: [],
            selectedRowKeys: []
          })
        }
      })
    }
  },
  effects: {
    *query({}, {call, put, select}) {
      let selectedDistributorId = yield select(({cartList}) => cartList.selectedDistributorId);
      if(!selectedDistributorId || (selectedDistributorId == '-1')){
        yield put({
          type: 'success',
          productsList: []
        })
      }else{
        let {result: data} = yield call(query,{
          distributorId: (selectedDistributorId == '-1' ? null : selectedDistributorId)
        });
        yield put({
          type: 'success',
          productsList: data
        })
      }
    },
    *updateCount({id, index, count}, {call, put, select}) {
      let data = yield call(updateCart, {
        shopCartId: id,
        number: count
      })
      let selectedRows = yield select(({cartList}) => cartList.selectedRows);
      let selectedRowKeys = yield select(({cartList}) => cartList.selectedRowKeys);
      yield put({
        type: 'setSelectedRowKeys',
        selectedRows,
        selectedRowKeys
      });
    },
    *deleteProducts({items}, {call, put, select}) {
      let ids = [];
      let productsList = yield select(({cartList}) => cartList.productsList);
      items.forEach((value) => {
        let itemIndex = productsList.indexOf(value);
        productsList.splice(itemIndex, 1);
        ids.push(value.id);
      })
      let data = yield call(deleteCart, {
        shopCartIds: ids
      })
      yield put({
        type: 'success',
        productsList
      });
      let keys = yield select(({cartList}) => cartList.selectedRowKeys);
      let _selectedRows = [];
      let _selectedRowKeys = [];
      productsList.forEach((value) => {
        if(keys.indexOf(value.id) > -1){
          _selectedRows.push(value);
          _selectedRowKeys.push(value.id);
        }
      })
      yield put({
        type: 'setSelectedRowKeys',
        selectedRows: _selectedRows,
        selectedRowKeys: _selectedRowKeys
      })
    },
    *goCartCaluate({selectedRowKeys}, {call, put, select}){
      let ids = selectedRowKeys.join("-");
      let selectedDistributorId = yield select(({cartList}) => cartList.selectedDistributorId);
      yield put(routerRedux.push(`/salesmarket/cartcaluate/1/${ids}`, {salesDistributorId: selectedDistributorId}));
    }
  },
  reducers: {
    success(state, {productsList}) {
      return{
        ...state,
        productsList
      }
    },
    setSelectedRowKeys(state, {selectedRowKeys, selectedRows}) {
      let totalChannelPrice = 0;
      let totalRetailPrice = 0;
      let totalPrice = 0;
      let count = 0;
      selectedRows.forEach((value, index) => {
        totalRetailPrice += (value.price * 10 * 10 * value.number);
        totalChannelPrice += (value.channelPrice * 10 * 10 * value.number);
        count += value.number;
        totalPrice = totalChannelPrice;
      })
      return{
        ...state,
        selectedRowKeys,
        selectedRows,
        totalRetailPrice: (totalRetailPrice/100).toFixed(2),
        totalChannelPrice: (totalChannelPrice/100).toFixed(2),
        totalPrice: (totalPrice/100).toFixed(2),
        count
      }
    },
    changeDistributor (state, {selectedDistributorId}) {
      return {
        ...state,
        selectedDistributorId
      }
    },
    reset(state, {selectedDistributorId}){
      return{
        ...state,
        selectedDistributorId,
        classifyList: [],
        searchClassifyKeyword: '',
        classifyId: null,
        productList: [],
        queryParam: {},
        detailModal: false,
        detailUrl: '',
        count: 0
      }
    }
  }
})
